import Koa from 'koa2';
import { router } from './middlewares/routerHandler';
// import bodyParser from 'koa-bodyparser';
import koaBody from 'koa-body'
import crossOriginHandler from './middlewares/crossOriginHandler'
import Application, { Context } from 'koa';
import logger from './utils/logger';
import fileHandler from './middlewares/fileHandler';
import session from 'koa-session-ts';
import verifyCodeHandler from './middlewares/verifyCodeHandler';
import jwtUtils from './utils/jwtUtils';
import { Config } from './types/global';
const app: Application = new Koa();
app.proxy = true; // 获取客户端真实地址
// app.use(bodyParser({
//   extendTypes: {
//     json: ['text/json'],
//   },
// }));
app.use(crossOriginHandler)
// 校验token
app.use(jwtUtils.validateToken.bind(jwtUtils))
app.use(session({
    cookieOptions: {
        httpOnly: true,
        maxAge: 1000 * 60 * 60 * 24, // one day
        overwrite: true,
        path: '/',
        secure: false,
        signed: false,
    },
}));
// 使用koa-body解析报文体
app.use(koaBody({
    multipart: true, // support formData
    parsedMethods: ['POST', 'PUT', 'PATCH', 'GET', 'HEAD', 'DELETE'], // parse method requestbody
    formidable: {
        maxFieldsSize: 250 * 1024 * 1024, // 限制请求body中字段的大小为250M
        maxFileSize: 250 * 1024 * 1024, // 设置文件上传大小为250M
        // uploadDir: path.resolve(global.config.get('uploadsPath')),// 上传目录,自定义上传则注释掉
        onFileBegin: (name, file) => {
            // todo 上传前dosomething,比如自定义文件名等
        },
        keepExtensions: true,// 保留文件扩展名
    },
    onError: (err, ctx: Context) => {
        logger.error('解析请求报文出错:', err)
    },
}));
app.use(verifyCodeHandler);
app.use(fileHandler);
app.use(router.routes()).use(router.allowedMethods())
const port = process.env.PORT || 80;
const host = (global.config as Config).get('domain');
app.listen(Number(port), () => {
    logger.info(`server run at http://${host}:${port}`)
    logger.info(`swagger run at http://${host}:${port}/swagger-html`)
})
// 处理内部异常
app.on('error', (err) => {
    logger.error(`onerror: ${err.stack || err.message}`);
});

// 处理未知异常
process.on('uncaughtException', (err) => {
    logger.error(`uncaughtException: ${err.stack || err.message}`);
});